import {Component, OnInit} from '@angular/core';
import {adSystemApiUrl, component_appid, redirect_uri} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';
import {Router} from '@angular/router';
import {Location} from '@angular/common';
import {URLSearchParams} from '@angular/http';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {AuthorizationPostParam, Authorization_token} from './authorization';

@Component({
  selector: 'app-authorization',
  templateUrl: 'authorization.component.html',
  styleUrls: ['authorization.component.scss']
})
export class AuthorizationComponent implements OnInit {
  public pre_auth_code = 'preauthcode@@@4XF4VfYo19rKLdA86BBgC2sL97T2BT8ri9E14cGI4LsfGEtIQaHISaJ6MawC5dAU';
  public authorization_url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=';
  public postParams = new AuthorizationPostParam;
  public authorization_info = new Authorization_token;
  public appletInfo;

  constructor(private httpService: HttpService, private router: Router, private location: Location, private localStorageService: LocalStorageService) {
  }

  ngOnInit() {
    this.appletInfo = this.localStorageService.getNowApplet();
    this.getAuthCallBack();
  }

  gotoWechatGetAuthorization() {
    // 获取微信预授权码
    const url = `${adSystemApiUrl}/v1/member/wechat/pre_auth_code`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        if (res.code === 2000) {
          this.pre_auth_code = res.data.pre_auth_code;
          const url = this.authorization_url + component_appid + '&pre_auth_code=' + this.pre_auth_code + '&redirect_uri=' + redirect_uri;
          window.location.href = url;
        } else {
          alert(res.message);
        }
      }
    );
  }

  // 获取微信预授权码
  // getPreAuthCode() {
  //   const url = `${adSystemApiUrl}/v1/member/wechat/pre_auth_code`;
  //   return this.httpService.httpGetAuth(url).subscribe(
  //       res => {
  //         if (res.code === 2000) {
  //           this.pre_auth_code = res.data.pre_auth_code;
  //         } else {
  //           alert(res.message);
  //         }
  //       }
  //   );
  // }

  // 获取url上的参数确定授权信息
  getAuthCallBack() {
    var addressUrl = location.search.slice(1);
    var searchParams = new URLSearchParams(addressUrl);

    let auth_code = searchParams.get('auth_code');
    let expires_in = searchParams.get('expires_in');
    if (auth_code) {
      this.postParams.applet_uuid = this.localStorageService.getNowApplet().applet_uuid;
      this.postParams.authorization_code = auth_code;
      const url = `${adSystemApiUrl}/v1/member/wechat/get_authorization_info`;

      return this.httpService.httpPostAuth(url, this.postParams).subscribe(
        res => {
          if (res.code === 2000) {
            this.authorization_info = res.data.authorization_info;
            this.authorization_info.expires_at = new Date().getTime() + this.authorization_info.expires_in * 1000;
            this.localStorageService.setAppletToken(this.authorization_info);
            alert("授权成功，您可前往发布小程序");

            const url = `${adSystemApiUrl}/v1/member/applets/detail?id=${this.appletInfo.id}`;
            return this.httpService.httpGetAuth(url).subscribe(
              res => {
                if (res.code === 2000) {
                  this.localStorageService.setNowApplet(res.data);
                  this.appletInfo = this.localStorageService.getNowApplet();
                }
              }
            )
          } else {
            alert(res.message);
          }
        }
      );
    } else {
      // alert('授权条件不足!');
    }
  }
}
